import React, { Component } from 'react'
import {List,Badge} from 'antd-mobile'
import {connect} from 'react-redux'

@connect(
    state => state
)
export default class Msg extends Component {
    getLast(arr){
        return arr[arr.length - 1]
    }
    render() {
        const msgGroup = {}
        this.props.chat.chatmsg.forEach(v=>{
            msgGroup[v.chatid] =  msgGroup[v.chatid] || []
            msgGroup[v.chatid].push(v)
        })
        const chatList = Object.values(msgGroup).sort((a,b)=>{
            const a_last = this.getLast(a).create_time
            const b_last = this.getLast(b).create_time
            return b_last - a_last
        })
        const userid = this.props.user._id


        return (
            <div>
                
                    {chatList.map(v=>{
                        const lastItem = this.getLast(v)
                        const targetId = v[0].from===userid?v[0].to:v[0].from
                        const unreadNum = v.filter(v=>!v.read && v.to===userid).length
                        return (
                            <List key={lastItem._id}>
                                <List.Item 
                                arrow="horizontal"
                                thumb={require(`../avatar-selector/img/${this.props.chat.users[targetId].avatar}.png`)}
                                extra={<Badge text={unreadNum}></Badge>}
                                onClick={()=>{
                                    this.props.history.push(`/chat/${targetId}`)
                                }}
                                >
                                    {lastItem.content}
                                    <List.Item.Brief>{this.props.chat.users[targetId].name}</List.Item.Brief>
                                </List.Item>
                            </List>  
                        )
                        
                    })}
                    
                  
            </div>
        )
    }
}
